using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Turret : MonoBehaviour
{

    [Header("Shooting")]
    public GameObject turret_head;

    [HideInInspector]
    public Animator anmi;
    // Start is called before the first frame update

    public Transform partToRotate;

    public Transform firePoint;

    private GameObject _target;

    private float attackDistance = 8.0f;
    void Awake()
    {
        anmi = turret_head.GetComponent<Animator>();
        Animation animation = turret_head.GetComponent<Animation>();
    }

    void Start()
    {
        InvokeRepeating("TargetEnemy", 0f, 0.5f);
    }

    // Update is called once per frame
    void Update()
    {
       if(_target != null)
        {
            Vector3 dir = _target.transform.position - transform.position;
            Quaternion lookRotation = Quaternion.LookRotation(dir);
            partToRotate.rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * 10f);
            //////partToRotate.rotation = rotation;
        }
    }

    void TargetEnemy()
    {
        if (_target == null)
        {
            BuilderManager.Instance.CheckAnemy(delegate (GameObject enemy)
            {
                if (Vector3.Distance(transform.position, enemy.transform.position) < attackDistance)
                {
                    _target = enemy;
                    _target.GetComponent<Enemy>().OnDie += delegate (GameObject curobj)
                    {
                        if (curobj != null && curobj == _target)
                        {
                            Debug.Log("sub event in CheckAnemy");
                            _target = null;
                        }
                    };

                    return true;
                }
                return false;
            });
        } 
        else
        {
            ShootEnemy();
        }
    }

    private void ShootEnemy()
    {
        GameObject bulletFire = Instantiate(BuilderManager.Instance.bullet, firePoint.position, firePoint.rotation);
        Bullet bullets = bulletFire.GetComponent<Bullet>();
        if(bullets != null)
        {
            bullets.Seek(_target);
        }
    }
}
